<template>
  <div class="login-container">
    <!-- 背景动画 -->
    <canvas id="login-bg" class="login-bg"></canvas>

    <!-- 背景渐变层 -->
    <div class="bg-overlay"></div>

    <!-- 装饰元素 -->
    <div class="decoration">
      <div class="palm-tree"></div>
      <div class="sun"></div>
    </div>

    <!-- 登录框 -->
    <div class="login-box">
      <div class="login-content">
        <h2 class="title">欢迎回来</h2>
        <p class="subtitle">开启您的心理咨询之旅</p>
        
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="用户名"
              type="text"
              tabindex="1"
              autocomplete="on"
              @change="handleUsernameChange"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              placeholder="密码"
              :type="passwordVisible ? 'text' : 'password'"
              tabindex="2"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
              <template #suffix>
                <el-icon 
                  class="password-icon" 
                  @click="passwordVisible = !passwordVisible"
                >
                  <View v-if="passwordVisible"/>
                  <Hide v-else/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <div class="form-options">
            <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
            <el-button 
              link 
              type="primary" 
              @click="handleForgotPassword"
            >
              忘记密码？
            </el-button>
          </div>

          <el-button 
            :loading="loading" 
            type="primary" 
            style="width: 100%; margin-bottom: 30px"
            @click.prevent="handleLogin"
          >
            登录
          </el-button>

          <div class="register-link">
            <span>还没有账号？</span>
            <router-link to="/register">立即注册</router-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, reactive } from 'vue'
import { User, Lock, View, Hide } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { initParticles } from '@/utils/particles'
import type { FormInstance } from 'element-plus'
import { getEmailByUsername } from '@/api/user'

const router = useRouter()
const route = useRoute()
const store = useStore()
const loading = ref(false)
const loginFormRef = ref<FormInstance>()
const passwordVisible = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    loading.value = true
    await loginFormRef.value.validate()
    
    console.log('开始登录流程...')
    
    // 发送登录请求时包含remember字段
    const { username, password, remember } = loginForm
    console.log('发送登录请求...')
    const res = await store.dispatch('user/login', { username, password, remember })
    console.log('登录请求成功:', res)
    
    // 获取用户信息
    console.log('获取用户信息...')
    await store.dispatch('user/getInfo')
    const userInfo = store.getters['user/userInfo']
    console.log('获取用户信息成功:', userInfo)
    
    // 登录成功后记录登录日志
    try {
      console.log('开始记录登录日志...')
      const logData = {
        userId: userInfo.id,
        username: username,
        userAgent: navigator.userAgent,
        status: 0,
        msg: '登录成功'
      }
      console.log('发送登录日志数据:', logData)
      await store.dispatch('user/recordLoginLog', logData)
      console.log('记录登录日志成功')
    } catch (error: any) {

      // 不阻止登录流程继续
    }
    
    const redirect = route.query.redirect?.toString() || '/dashboard'
    router.push(redirect)
    ElMessage.success('登录成功')
  } catch (error: any) {
    console.error('登录失败:', error)

  } finally {
    loading.value = false
  }
}

const handleForgotPassword = async () => {
  if (!loginForm.username) {
    ElMessage.warning('请先输入用户名再进行密码重置')
    return
  }

  try {
    // 先获取用户邮箱
    const response = await fetch(`/api/auth/email?username=${loginForm.username}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    if (result.code === 200 && result.data) {
      router.push({
        path: '/forgot-password',
        query: { 
          username: loginForm.username,
          email: result.data
        }
      })
    } else {
      ElMessage.error('该用户名不存在，请检查后重试')
    }
  } catch (error: any) {
    ElMessage.error('该用户名不存在，请检查后重试')
  }
}

const handleUsernameChange = () => {
  // 用户名变化时可以在这里添加其他逻辑
}

// 初始化粒子效果
let cleanup: (() => void) | undefined
onMounted(() => {
  cleanup = initParticles('login-bg')
})

onBeforeUnmount(() => {
  if (cleanup) {
    cleanup()
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);
  position: relative;
  overflow: hidden;

  .bg-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to bottom,
      rgba(255, 183, 77, 0.2) 0%,
      rgba(255, 167, 77, 0.3) 50%,
      rgba(255, 152, 77, 0.4) 100%
    );
    z-index: 1;
  }

  .decoration {
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 0;
    pointer-events: none;

    .sun {
      position: absolute;
      top: 15%;
      right: 10%;
      width: 100px;
      height: 100px;
      background: radial-gradient(
        circle at center,
        #ffd700 0%,
        #ff8c00 60%,
        transparent 100%
      );
      border-radius: 50%;
      opacity: 0.8;
      animation: glow 3s infinite alternate;
    }

    .palm-tree {
      position: absolute;
      bottom: 0;
      left: 5%;
      width: 200px;
      height: 300px;
      background-image: url('@/assets/palm-tree.png');
      background-size: contain;
      background-repeat: no-repeat;
      background-position: bottom;
      opacity: 0.8;
      transform-origin: bottom;
      animation: sway 5s ease-in-out infinite;
    }
  }

  .login-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
  }

  .login-box {
    position: relative;
    z-index: 3;
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.85);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    animation: slideIn 0.6s ease;

    .login-content {
      .title {
        font-size: 28px;
        font-weight: 600;
        text-align: center;
        margin-bottom: 8px;
        background: linear-gradient(45deg, #ff8c00, #ff6b6b);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
      }

      .subtitle {
        text-align: center;
        color: #666;
        margin-bottom: 32px;
      }

      .login-form {
        .el-input {
          --el-input-hover-border-color: #ff8c00;
          --el-input-focus-border-color: #ff8c00;
        }

        .form-options {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 24px;
          
          .el-checkbox__label {
            color: #606266;
          }

          .forgot-password {
            color: var(--el-color-primary);
            padding: 0;
            
            &:hover {
              color: var(--el-color-primary-light-3);
            }
          }
        }

        .login-button {
          width: 100%;
          height: 44px;
          margin-top: 20px;
          font-size: 16px;
          background: linear-gradient(45deg, #ff8c00, #ff6b6b);
          border: none;
          transition: all 0.3s;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
          }
        }

        .register-link {
          margin-top: 24px;
          text-align: center;
          color: #666;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 4px;
          font-size: 14px;

          :deep(.el-link) {
            margin: 0;
            height: auto;
            line-height: 1;
            font-size: 14px;
          }
        }
      }
    }
  }
}

@keyframes glow {
  from {
    box-shadow: 0 0 20px #ffd700;
  }
  to {
    box-shadow: 0 0 40px #ff8c00;
  }
}

@keyframes sway {
  0%, 100% {
    transform: rotate(-2deg);
  }
  50% {
    transform: rotate(2deg);
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式调整
@media (max-width: 480px) {
  .login-container {
    .login-box {
      width: 90%;
      margin: 0 20px;
      padding: 30px 20px;
    }
  }
}

:deep(.el-input) {
  --el-input-height: 40px;
  
  .el-input__wrapper {
    padding: 0 15px;
  }
  
  .el-input__prefix {
    display: flex;
    align-items: center;
    color: #909399;
  }
}

.password-icon {
  cursor: pointer;
  color: #909399;
}
</style>

